<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\printmanager\Goods as GoodsModel;
use app\common\model\printmanager\Order as OrderModel;
use app\common\model\User;
use think\Db;
use think\Config;
use fast\Random;
use think\Response;
use think\Session;
use app\common\service\Payment;


class Order extends Api
{
  protected $noNeedLogin = [];
  protected $noNeedRight = '*';

  public function _initialize()
  {
    parent::_initialize();
  }

  /**
   *
   */
  public function index()
  {
    $this->success('', ['welcome' => '123']);
  }


  /*
     * 确认订单
     * goods_data {
     *  cart_id,goods_id,goods_num
     * }
     */
  public function confirmOrder()
  {
    $user_id = $this->auth->id;
    $total_amount = 0;  //订单总额
    $allow_golds = 0;   //订单可用金币

    $goods_data = input('goods_data/s');

    try {
      $goods_data = json_decode(htmlspecialchars_decode($goods_data), true);
    } catch (\Exception $th) {
      $this->error('商品参数有误');
    }


    if (!$goods_data) {
      $this->error('商品参数有误');
    }

    $goods_list = [];
    $shipping_price = 0;

    foreach ($goods_data as $key => $goods) {
      if (!isset($goods['goods_id'])) {
        $this->error('商品参数有误');
      }
      $goods_info = GoodsModel::where(array('id' => $goods['goods_id']))->field('id, name, price, store,unit, shipping_price, gold_num, introduce, images')->find();

      if (!$goods_info) {
        $this->error('商品参数有误');
      }
      $goods_info['num'] = isset($goods['goods_num']) ? $goods['goods_num'] : 1;
      $goods_info['file_list'] = $goods_info->file_list;
      $goods_info['amount'] = bcmul($goods_info['price'], $goods_info['num'], 2);
      $goods_list[] = $goods_info;
      $total_amount = bcadd($total_amount, $goods_info['amount'], 2);
      $allow_golds += $goods_info['gold_num'] * $goods_info['num'];
      $shipping_price += bcmul($goods_info['shipping_price'], $goods_info['num'], 2);
    }

    $user_golds_num = $this->auth->getUserinfo()['money'];  //用户拥有金币

    $allow_golds = $user_golds_num >= $allow_golds ? $allow_golds : $user_golds_num;  //允许使用最大金币量
    $allow_golds_amount = round($allow_golds / config('site.rmb_rate'), 2);
    $use_gold_amount = $total_amount - $allow_golds_amount;

    $result = [
      'address' => User::getDefaultAddress($this->auth->id),
      'goods_list' => $goods_list,
      'shipping_price' => bcadd($shipping_price, 0, 2),
      'total_amount' => bcadd($total_amount, $shipping_price, 2) ,
      'total_amount_noshipping' => $total_amount,
      'allow_golds' => $allow_golds,
      'allow_golds_amount' => $allow_golds_amount,
      'use_gold_amount' => $use_gold_amount
    ];

    $this->success('确认订单数据', $result);
  }

  /*
     * 提交订单
     */
  public function submitOrder()
  {
    $user_id = $this->auth->id;

    $total_amount = 0;  //订单总额
    $allow_golds = 0;   //订单可用金币

    $goods_data = input('goods_data/s');

    try {
      $goods_data = json_decode(htmlspecialchars_decode($goods_data), true);
    } catch (\Exception $th) {
      $this->error('商品参数有误');
    }


    if (!$goods_data) {
      $this->error('商品参数有误');
    }


    // 0 快递 1自提
    $shipping_type = input('shipping_type/d', 0);
    $address_id = input('address_id/d', 0);
    if ($shipping_type == 0) {
      if ($address_id == 0) {
        $this->error('请选择收货地址');
      }
    } else {
      $shipping_type = 1;
    }

    $remark = input('remark/s', '');
    $use_gold = input('use_gold/d', 0);

    $goods_list = [];
    $goods_ids = [];

    $shipping_price = 0;

    Db::startTrans();

    foreach ($goods_data as $key => $goods) {
      if (!isset($goods['goods_id'])) {
        Db::rollback();
        $this->error('商品参数有误');
      }
      $goods_info = GoodsModel::where(array('id' => $goods['goods_id']))->field('id, name, price, store,unit, shipping_price, gold_num, introduce, images')->find();

      if (!$goods_info) {
        Db::rollback();
        $this->error('商品参数有误');
      }

      $goods_info['num'] = isset($goods['goods_num']) ? $goods['goods_num'] : 1;

      if ($goods_info['store'] < $goods_info['num']) {
        Db::rollback();
        $this->error("{$goods_info['name']}库存剩余{$goods_info['store']}{$goods_info['unit']}");
      }

      $goods_info['amount'] = bcmul($goods_info['price'], $goods_info['num'], 2);
      $goods_list[] = $goods_info;
      $total_amount = bcadd($total_amount, $goods_info['amount'], 2);
      $allow_golds += $goods_info['gold_num'] * $goods_info['num'];

      $goods_ids[] = $goods_info['id'];
      $shipping_price += $goods_info['shipping_price'] * $goods_info['num'];

      #扣除库存
      GoodsModel::where(array('id' => $goods['goods_id']))->setDec('store', $goods_info['num']);
    }

    $user_golds_num = $this->auth->getUserinfo()['money'];  //用户拥有金币
    $allow_golds = $user_golds_num >= $allow_golds ? $allow_golds : $user_golds_num;  //允许使用最大金币量
    $allow_golds_amount = round($allow_golds / config('site.rmb_rate'), 2);

    $order_data['user_id'] = $user_id;
    $order_data['amount'] = $total_amount;
    $order_data['gold_num'] = $use_gold == 1 ? $allow_golds : 0;
    $order_data['gold_amount'] = $use_gold == 1 ? $allow_golds_amount : 0;
    $order_data['shipping_type'] = $shipping_type;
    $order_data['shipping_price'] = $shipping_type == 0 ? $shipping_price : 0;
    $order_data['remark'] = $remark;
    $order_data['address_id'] = $address_id;
    $order_data['order_no'] = 'hb' . date('ymdhi') . Random::numeric(8);
    
    $result = OrderModel::create($order_data);
    if (!$result) {
      Db::rollback();
      $this->error('操作失败');
    }

    $order_goods_list = array();
    foreach ($goods_list as $key => $val) {
      $order_goods['order_id'] = $result['id'];
      $order_goods['goods_id'] = $val['id'];
      $order_goods['num'] = $val['num'];
      $order_goods['price'] = $val['price'];
      $order_goods_list[] = $order_goods;
    }

    $is_success_ins = Db::name('self_order_goods')->insertAll($order_goods_list);
    if ($is_success_ins === false) {
      Db::rollback();
      $this->error('操作失败');
    }
    if ($use_gold == 1 && $allow_golds > 0) {
      $dec_money = User::money((0 - $allow_golds), $user_id, '下单消费');  //金币抵扣
      if ($dec_money === false) {
        Db::rollback();
        $this->error('操作失败');
      }
    }

    #删除购物车的同商品
    Db::name('self_cart')->where(array(
      'user_id' => $user_id,
      'goods_id' => ['in', $goods_ids]
    ))->delete();

    Db::commit();

    $result = OrderModel::get($result['id']);

    $return = [
      'amount' => $result['amount'],
      'real_amount' => $result['real_amount'],
      'shipping_price' => $result['shipping_price'],
      'gold_amount'  => $result['gold_amount'],
      'order_no'  => $result['order_no']
    ];

    $this->success('提交订单', $return);
  }

  /*
     * 我的订单列表
     */
  public function orderList()
  {
    $user_id = $this->auth->getUserinfo()['id'];
    $status = input('status/d', -1);
    $where['user_id'] = $user_id;
    if ($status != -1) {
      $where['status'] = $status;
    }
    $order = 'id DESC';
    $order_list = OrderModel::where($where)
      ->order($order)
      ->paginate()
      ->each(function ($item, $key) {
        $item['order_goods'] = $item->order_goods;
      });

    $this->success('订单列表', $order_list);
  }

  /*
     * 待评价商品列表
     */
  public function wait_comment()
  {
    $user_id = $this->auth->getUserinfo()['id'];
    $field = 'order_goods.id, order_goods.goods_id, order_goods.price, order_goods.num, 
                goods.name, order_goods.order_id, order_goods.is_evaluate';
    $where = ['order.user_id' => $user_id, 'order_goods.is_evaluate' => 0, 'order.status' => 3];
    $order_goods = Db::name('self_order_goods')->alias('order_goods')
      ->join('hb_self_order order', 'order_goods.order_id = order.id')
      ->field($field)
      ->where($where)
      ->paginate()
      ->each(function ($item, $key) {
        $item['order_goods'] = $item->order_goods;
        return $item;
      })
      ->toArray();
    $this->success('待评价商品列表', $order_goods);
  }

  /*
     * 订单签收
     */
  public function receiveOrder()
  {
    $user_id = $this->auth->getUserinfo()['id'];
    $id = input('id/d', 0);
    $where['user_id'] = $user_id;
    $where['id'] = $id;
    $order_info = OrderModel::where($where)->field('id, status')->find();

    if (!$order_info) {
      $this->error('订单信息有误');
    }
    if ($order_info['status'] != 2) {
      $this->error('该订单不能签收');
    }

    $is_success = OrderModel::where(array('id' => $id))->update(array('status' => 3));
    if ($is_success === false) {
      $this->error('操作失败');
    }

    $this->success('操作成功');
  }

  /*
     * 评价商品
     */
  public function commentGoods()
  {
    $user_id = $this->auth->getUserinfo()['id'];
    $id = input('id/d', 0);
    $field = 'order_goods.id, order_goods.goods_id, order_goods.order_id, order_goods.is_evaluate, order.status';
    $where = ['order.user_id' => $user_id, 'order_goods.id' => $id];
    $order_goods = Db::name('self_order_goods')->alias('order_goods')
      ->join('hb_self_order order', 'order_goods.order_id = order.id')
      ->field($field)
      ->where($where)
      ->find();
    if ($order_goods['status'] != 3) {
      $this->error('操作失败, 订单未签收');
    }
    if ($order_goods['is_evaluate'] == 1) {
      $this->error('操作失败, 商品已评价');
    }

    $data = $this->request->post();
    unset($data['token']);
    if(isset($data['share_from'])) unset($data['share_from']);
    $data['goods_id'] = $order_goods['goods_id'];
    $data['user_id'] = $user_id;
    $data['order_id'] = $order_goods['order_id'];
    $data['order_goods_id'] = $id;
    $data['createtime'] = time();
    Db::startTrans();
    $comment_id = Db::name('self_goods_comment')->insertGetId($data);
    if (!$comment_id) {
      Db::rollback();
      $this->error('操作失败');
    }
    $is_success = Db::name('self_order_goods')->where(array('id' => $id))->update(array('is_evaluate' => 1));
    if ($is_success === false) {
      Db::rollback();
      $this->error('操作失败');
    }
    Db::commit();
    $this->success('操作成功');
  }

  /*
     * 发起支付接口
     */
  public function pay()
  {
    $order_no = input('order_no/s', '');
    if (!$order_no) {
      $this->error('订单号不能为空');
    }

    $order_prefix = Payment::getOrderPrefix($order_no);
    try {
      if ($order_prefix == 'HB') {
        // 印刷订单
        $res = Payment::getPrintOrder($order_no, $this->auth->id);
      } elseif ($order_prefix == 'AD') {
        // 广告订单
        $res = Payment::getAdOrder(0, $order_no, $this->auth->id);
      }
    } catch (\Exception $e) {
      // var_dump([
      //   'msg' => $e->getMessage(),
      //   'file' => $e->getFile(),
      //   'line' => $e->getLine(),
      //   'router' => $e->getTrace(),
      // ]);die;
      $this->error($e->getMessage());
    }

    $this->success('payment', $res);
  }

  /**
   * 订单详情
   */
  public function detail($id){
    $where['user_id'] = $this->auth->id;
    $where['id'] = $id;
    $order_info = OrderModel::where($where)->find();

    if(!$order_info){
      $this->error("订单不存在");
    }

    $order_info->order_goods = $order_info->order_goods;
    $order_info->address = $order_info->address;

    $this->success("detail", $order_info);

  }

  /**
   * 取消订单
   */
  public function close(){
    $id = input('id/d', 0);
    $where['user_id'] = $this->auth->id;
    $where['id'] = $id;
    $order_info = OrderModel::where($where)->find();

    if (!$order_info) {
      $this->error('订单信息有误');
    }
    if ($order_info['status'] != 0) {
      $this->error('该订单不能关闭');
    }

    try {
      $is_success = Payment::printOrderClose($order_info);
    } catch (\Exception $e) {
      $this->error($e->getMessage());
    }

    
    if ($is_success === false) {
      $this->error('操作失败');
    }

    $this->success('操作成功');
  }
}
